<template>
  <div>
    <!-- 测试用：直接渲染盾牌图标 -->
    <el-icon style="font-size:48px;color:#40a9ff"><ShieldCheck /></el-icon>
  </div>
  <el-icon style="font-size:48px;color:#40a9ff"><ShieldCheck /></el-icon>
  <div class="dashboard">
    <!-- 编辑模式：显示个人信息编辑界面 -->
    <div v-if="isEditMode" class="edit-mode">
      <div class="edit-header">
        <el-button @click="exitEditMode" icon="ArrowLeft" link>
          返回个人中心
        </el-button>
      </div>
      <UserProfileEdit />
    </div>
    <!-- 修改密码模式：显示修改密码界面 -->
    <div v-else-if="isChangePasswordMode" class="edit-mode">
      <div class="edit-header">
        <el-button @click="exitEditMode" icon="ArrowLeft" link>
          返回个人中心
        </el-button>
      </div>
      <ChangePassword @success="handlePasswordChangeSuccess" />
    </div>
    <!-- 主内容：只有都不是编辑模式时才显示 -->
    <div v-else>
      <!-- 账户信息卡片 -->
      <div class="account-info-card">
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="user-avatar">
              <el-avatar
                  :size="120"
                  :src="resolveAvatarUrl(userInfo.avatar)"
                  :icon="!userInfo.avatar ? 'User' : undefined"
              >
                {{ !userInfo.avatar && userInfo.name ? userInfo.name.charAt(0) : '' }}
              </el-avatar>
              <h3>{{ userInfo.name }}</h3>
              <p class="user-role">{{ getRoleDisplayName(userInfo.role) }}</p>
              <el-tag :type="getRoleTagType(userInfo.role)" size="large">
                {{ getRoleDisplayName(userInfo.role) }}
              </el-tag>
            </div>
          </el-col>
          <el-col :span="16">
            <div class="account-details">
              <h4>账户详情</h4>
              <el-descriptions :column="2" border>
                <el-descriptions-item label="用户名">{{ userInfo.username }}</el-descriptions-item>
                <el-descriptions-item label="姓名">{{ userInfo.name }}</el-descriptions-item>
                <el-descriptions-item label="邮箱">{{ userInfo.email || '未设置' }}</el-descriptions-item>
                <el-descriptions-item label="手机号">{{ userInfo.phone || '未设置' }}</el-descriptions-item>
                <el-descriptions-item label="注册时间">{{ userInfo.registerTime || '2024-01-01' }}</el-descriptions-item>
                <el-descriptions-item label="最后登录">{{ userInfo.lastLogin || '2024-12-19 09:30' }}</el-descriptions-item>
              </el-descriptions>
            </div>
          </el-col>
        </el-row>
      </div>
      <!-- 账户管理模块 -->
      <div class="account-modules">
        <el-row :gutter="20">
          <el-col :span="12" v-for="module in accountModules" :key="module.id">
            <div class="module-card" @click="handleModuleClick(module)">
              <div class="module-icon">
                <el-icon v-if="module.title === '修改信息'">
                  <Edit />
                </el-icon>
                <el-icon v-else-if="module.title === '修改密码'">
                  <Lock />
                </el-icon>
              </div>
              <h4>{{ module.title }}</h4>
              <p>{{ module.description }}</p>
            </div>
          </el-col>
        </el-row>
      </div>
      <!-- AI客服对话模块 -->
      <div class="ai-chat-section card-width-align">
        <AiChatDialog :user-avatar="userInfo.avatar" />
      </div>
      <!-- 账户安全状态 -->
      <div class="security-section">
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="card">
              <div class="card-header">
                <h3 class="card-title">
                  <el-icon><User /></el-icon>
                  账户安全
                </h3>
              </div>
              <div class="card-content">
                <div class="security-items">
                  <div class="security-item">
                    <div class="security-info">
                      <h5>密码强度</h5>
                      <p>建议定期更换密码</p>
                    </div>
                    <el-progress :percentage="85" :color="getProgressColor(85)" />
                  </div>
                  <div class="security-item">
                    <div class="security-info">
                      <h5>两步验证</h5>
                      <p>启用两步验证提高安全性</p>
                    </div>
                    <el-switch v-model="security.twoFactor" />
                  </div>
                  <div class="security-item">
                    <div class="security-info">
                      <h5>登录设备</h5>
                      <p>当前在线设备数量</p>
                    </div>
                    <el-tag type="info">{{ security.onlineDevices }} 台</el-tag>
                  </div>
                </div>
              </div>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="card">
              <div class="card-header">
                <h3 class="card-title">
                  <el-icon><Setting /></el-icon>
                  偏好设置
                </h3>
              </div>
              <div class="card-content">
                <div class="preference-items">
                  <div class="preference-item">
                    <span>侧边栏自动收起</span>
                    <el-switch v-model="preferences.autoCollapse" />
                  </div>
                  <div class="preference-item">
                    <span>主题模式</span>
                    <el-select v-model="preferences.theme" size="small" style="width: 120px;">
                      <el-option label="浅色" value="light" />
                      <el-option label="深色" value="dark" />
                    </el-select>
                  </div>
                </div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
      <!-- 账户活动记录 -->
      <div class="activity-section">
        <RecentActivity />
      </div>

      <!-- 维修申请记录 -->
    </div>
  </div>
</template>

<script>
import { ref, computed, watch, onMounted } from 'vue'
import { useStore } from 'vuex'
import axios from 'axios'
import AiChatDialog from "@/components/AiChatDialog.vue";
import UserProfileEdit from '@/components/UserProfileEdit.vue'
import ChangePassword from '@/components/ChangePassword.vue'
import RecentActivity from '@/components/RecentActivity.vue'
import { ElMessage } from 'element-plus'
import { resolveAvatarUrl } from '@/utils/avatar'
import {
  Edit,
  Lock,
  Setting,
  ShieldCheck,
  User
} from '@element-plus/icons-vue'

export default {
  name: 'UserDashboard',
  components: {
    AiChatDialog,
    UserProfileEdit,
    ChangePassword,
    RecentActivity,
    Edit,
    Lock,
    Setting,
    ShieldCheck,
    User
  },
  setup() {
    const store = useStore()
    const isEditMode = ref(false)
    const isChangePasswordMode = ref(false)

    const userInfo = computed(() => {
      const user = store.state.user.userInfo || store.state.user
      console.log('Dashboard userInfo computed - store state:', store.state.user)
      console.log('Dashboard userInfo computed - user:', user)
      return {
        name: user.name || user.username || '访客用户',
        avatar: user.avatar || '',
        role: user.role || '',
        username: user.username || '',
        email: user.email || (user.username ? user.username + '@example.com' : 'user@example.com'),
        phone: user.phone || '',
        registerTime: user.registerTime || '',
        lastLogin: user.lastLogin || ''
      }
    })

    const getRoleDisplayName = (role) => {
      const roleNames = {
        student: '学生',
        teacher: '教师',
        admin: '管理员',
        staff: '后勤人员',
        STUDENT: '学生',
        TEACHER: '教师',
        ADMIN: '管理员',
        STAFF: '后勤人员',
        guest: '访客'
      }
      return roleNames[role] || '未知'
    }

    const getRoleTagType = (role) => {
      const tagTypes = {
        student: 'success',
        teacher: 'warning',
        admin: 'danger',
        staff: 'info',
        STUDENT: 'success',
        TEACHER: 'warning',
        ADMIN: 'danger',
        STAFF: 'info',
        guest: 'info'
      }
      return tagTypes[role] || 'info'
    }

    // 账户管理模块
    const accountModules = ref([
      {
        id: 1,
        title: '修改信息',
        description: '更新个人基本信息',
        icon: Edit,
        action: 'editInfo'
      },
      {
        id: 2,
        title: '修改密码',
        description: '更改账户密码',
        icon: Lock,
        action: 'changePassword'
      },
    ])

    // 安全设置
    const security = ref({
      twoFactor: false,
      onlineDevices: 2
    })

    // 偏好设置
    const preferences = ref({
      autoCollapse: localStorage.getItem('autoCollapse') === 'true',
      theme: localStorage.getItem('themeMode') || 'light'
    })

    // 维修申请数据
    const repairApplications = ref([])

    // 监听变化，写入localStorage并派发事件
    watch(() => preferences.value.autoCollapse, val => {
      localStorage.setItem('autoCollapse', val)
      window.dispatchEvent(new CustomEvent('autoCollapseChange', { detail: val }))
    })
    watch(() => preferences.value.theme, val => {
      localStorage.setItem('themeMode', val)
      window.dispatchEvent(new CustomEvent('themeModeChange', { detail: val }))
    })
    onMounted(() => {
      window.dispatchEvent(new CustomEvent('autoCollapseChange', { detail: preferences.value.autoCollapse }))
      window.dispatchEvent(new CustomEvent('themeModeChange', { detail: preferences.value.theme }))
      fetchRepairApplications()
    })

    // 最近活动 - 现在使用RecentActivity组件

    const getProgressColor = (percentage) => {
      if (percentage >= 80) return '#67c23a'
      if (percentage >= 60) return '#e6a23c'
      return '#f56c6c'
    }

    // 获取维修申请列表
    const fetchRepairApplications = async () => {
      try {
        const userId = localStorage.getItem('userId')
        if (userId) {
          const res = await axios.get(`/api/repair/user/${userId}`)
          repairApplications.value = res.data || []
        }
      } catch (error) {
        console.error('获取维修申请失败', error)
      }
    }

    // 获取维修状态类型
    const getRepairStatusType = (status) => {
      const typeMap = {
        '待审批': 'warning',
        '已分配': 'info',
        '维修中': 'primary',
        '完成': 'success',
        '已取消': 'danger'
      }
      return typeMap[status] || 'info'
    }

    // 格式化日期
    const formatDate = (dateStr) => {
      if (!dateStr) return ''
      const d = new Date(dateStr)
      return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
    }

    const handleModuleClick = (module) => {
      if (module.action === 'editInfo') {
        isEditMode.value = true
        isChangePasswordMode.value = false
      } else if (module.action === 'changePassword') {
        isEditMode.value = false
        isChangePasswordMode.value = true
      } else {
        ElMessage.info(`${module.title}功能开发中...`)
      }
    }

    const exitEditMode = () => {
      isEditMode.value = false
      isChangePasswordMode.value = false
    }

    const handlePasswordChangeSuccess = () => {
      ElMessage.success('密码修改成功，请重新登录')
      // 可以选择是否自动登出
      store.dispatch('user/logout').then(() => {
        window.location.href = '/login'
      })
    }

    const menuItems = computed(() => {
      const items = [
        { name: '首页', path: '/dashboard' },
        { name: '通知公告', path: '/notice' },
        { name: '维修申请', path: '/repair-application' },
        { name: '个人中心', path: '/user-profile' }
      ]
      if (userInfo.value.role === 'ADMIN' || userInfo.value.role === 'STAFF') {
        items.push({ name: '维修管理', path: '/repair-manage' })
      }
      if (userInfo.value.role === 'ADMIN') {
        items.push({ name: '历史日志', path: '/log-history' })
      }
      return items
    })

    return {
      isEditMode,
      isChangePasswordMode,
      userInfo,
      accountModules,
      security,
      preferences,
      repairApplications,
      getRoleDisplayName,
      getRoleTagType,
      getProgressColor,
      fetchRepairApplications,
      getRepairStatusType,
      formatDate,
      handleModuleClick,
      exitEditMode,
      resolveAvatarUrl,
      handlePasswordChangeSuccess,
      menuItems
    }
  }
}
</script>

<style scoped>
.dashboard {
  max-width: 1200px;
  margin: 0 auto;
}

.account-info-card {
  background: white;
  border-radius: 8px;
  padding: 30px;
  margin-bottom: 30px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.user-avatar {
  text-align: center;
}

.user-avatar h3 {
  margin: 16px 0 8px;
  color: var(--text-color);
}

.user-role {
  color: var(--text-color-secondary);
  font-size: 14px;
}

.account-details {
  margin-top: 20px;
}

.account-details h4 {
  margin-bottom: 16px;
  color: var(--text-color);
}

.account-details .el-descriptions {
  margin-bottom: 0;
}

.account-details .el-descriptions .el-descriptions-item {
  padding: 12px 0;
}

.account-details .el-descriptions .el-descriptions-item label {
  color: var(--text-color-secondary);
  font-size: 14px;
}

.account-details .el-descriptions .el-descriptions-item .el-tag {
  margin-left: 16px;
}

.account-modules {
  margin-bottom: 30px;
}

.module-card {
  background: white;
  border-radius: 8px;
  padding: 30px 20px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.module-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.module-icon {
  margin-bottom: 16px;
  color: var(--primary-color);
}

.module-card h4 {
  margin-bottom: 12px;
  color: var(--text-color);
}

.module-card p {
  color: var(--text-color-secondary);
  line-height: 1.6;
}

.security-section {
  margin-bottom: 30px;
}

.card {
  background: white;
  border-radius: 8px;
  padding: 30px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.card-header {
  margin-bottom: 20px;
}

.card-header h3 {
  margin: 0;
  color: var(--text-color);
}

.card-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.security-items {
  width: 50%;
}

.security-item {
  margin-bottom: 16px;
}

.security-info {
  margin-bottom: 8px;
}

.security-info h5 {
  color: var(--text-color);
  font-size: 14px;
}

.security-info p {
  color: var(--text-color-secondary);
  font-size: 12px;
}

.preference-items {
  width: 50%;
}

.preference-item {
  margin-bottom: 16px;
}

.preference-item span {
  margin-right: 16px;
  color: var(--text-color);
  font-size: 14px;
}

.activity-section {
  margin-bottom: 30px;
}

.repair-section {
  margin-top: 30px;
}

.repair-item {
  padding: 10px;
  background: #f8f9fa;
  border-radius: 6px;
}

.repair-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.repair-no {
  font-weight: bold;
  color: #303133;
}

.repair-content {
  color: #606266;
}

.repair-type {
  font-weight: 500;
  margin-bottom: 4px;
}

.repair-location {
  font-size: 12px;
  color: #909399;
  margin-bottom: 4px;
}

.repair-description {
  font-size: 12px;
  color: #909399;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.empty-state {
  text-align: center;
  padding: 40px 0;
}

.el-timeline {
  padding: 0;
}

.el-timeline-item {
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.el-timeline-item:last-child {
  border-bottom: none;
}

.el-timeline-item .el-timeline-item__tail {
  display: none;
}

.el-timeline-item .el-timeline-item__node {
  top: 12px;
}

.el-timeline-item .el-timeline-item__node-tail {
  display: none;
}

.el-timeline-item .el-timeline-item__node-content {
  padding: 0;
}

.el-timeline-item .el-timeline-item__node-content h4 {
  margin: 0;
  color: var(--text-color);
}

.el-timeline-item .el-timeline-item__node-content p {
  margin: 8px 0 0;
  color: var(--text-color-secondary);
}

@media (max-width: 768px) {
  .account-info-card {
    padding: 20px;
  }

  .account-modules .el-col {
    margin-bottom: 15px;
  }

  .security-section .el-col {
    margin-bottom: 20px;
  }
}

body.dark-theme .module-card {
  background: #181c20 !important;
  color: #fff !important;
  border-radius: 14px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.18);
  margin-bottom: 24px;
  padding: 32px 0 24px 0 !important;
  min-height: 180px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  transition: box-shadow 0.3s, background 0.3s, transform 0.3s;
}
body.dark-theme .module-card h4 {
  color: #fff !important;
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 10px;
}
body.dark-theme .module-card p {
  color: #aaa !important;
  font-size: 15px;
  margin: 0;
}
body.dark-theme .module-icon {
  color: #40a9ff !important;
  font-size: 38px !important;
  margin-bottom: 18px;
  transition: color 0.3s;
}
body.dark-theme .module-card:hover {
  background: #23272e !important;
  box-shadow: 0 8px 32px rgba(64,158,255,0.25);
  transform: translateY(-6px) scale(1.03);
}
body.dark-theme .module-card:hover .module-icon {
  color: #69c0ff !important;
}
.card-width-align {
  max-width: 1200px;
  margin: 0 auto 30px auto;
  padding-left: 0;
  padding-right: 0;
}
</style> 